package com.yanqu.road.server.manager.union.honors;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.entity.union.honors.UnionActivityHonorsReward;
import com.yanqu.road.entity.union.honors.eHonorsActivityType;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.union.cross.CrossUnionHonorsProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionHonorsActivityMgr extends TempMgr {
    //  -----<活动id,<rank,奖励>> 4.9旗帜优化
    static Map<Integer, Map<Integer, UnionActivityHonorsReward>> rewardMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    //增加活动商会到发奖候补中 把unionUidList按照商会排行榜顺序传进来
    public static void add(int activityId, List<String> unionUidList, int activityType, int activityChildType, List<Long> serverList,long serverId) {
        eHonorsActivityType eHonorsType = eHonorsActivityType.getHonorsType(activityType, activityChildType);
        if (eHonorsType == null) {
            return;
        }

        Map<Integer, UnionActivityHonorsReward> rankRewardMap = rewardMap.get(activityId);
        if (rankRewardMap == null) {
            synchronized (rewardMap) {
                rankRewardMap = rewardMap.get(activityId);
                if (rankRewardMap == null) {
                    rankRewardMap = new ConcurrentHashMap<>();
                    rewardMap.put(activityId, rankRewardMap);
                }
            }
            getLogger().debug("----------------- add reward {}", JSON.toJSONString(rankRewardMap));
        }
        if (unionUidList == null) {
            getLogger().error("活动id={}，获取排行榜发放荣誉点失败", activityId);
            return;
        }
        for (int i = 0; i < unionUidList.size(); i++) {
            String unionUid = unionUidList.get(i);
            //排名从1开始
            UnionActivityHonorsReward honorsReward = rankRewardMap.get(i + 1);
            if (honorsReward == null) {
                honorsReward = new UnionActivityHonorsReward();
                honorsReward.setActivityId(activityId);
                honorsReward.setUnionUid(unionUid);
                honorsReward.setActivityType(activityType);
                honorsReward.setActivityChildType(activityChildType);
                honorsReward.setServerList(serverList);
                honorsReward.setServerId(serverId);
                honorsReward.setRank(i + 1);
                rankRewardMap.put(i + 1, honorsReward);
            } else {
                //无uid情况
                if (!honorsReward.isSend() && StringUtils.isNullOrEmpty(honorsReward.getUnionUid())) {
                    honorsReward.setUnionUid(unionUid);
                }
                //uid不同情况
                if (!honorsReward.isSend() && !honorsReward.getUnionUid().equals(unionUid)) {
                    honorsReward.setUnionUid(unionUid);
                }
            }
        }
    }

    public static void sendReward() {

        for (Map.Entry<Integer, Map<Integer, UnionActivityHonorsReward>> activityRewardEntry : rewardMap.entrySet()) {
            Map<Integer, UnionActivityHonorsReward> activityHonorsRewardMap = activityRewardEntry.getValue();
            for (Map.Entry<Integer, UnionActivityHonorsReward> rewardEntry : activityHonorsRewardMap.entrySet()) {
                UnionActivityHonorsReward reward = rewardEntry.getValue();
                if (reward.isSend()) {
                    continue;
                }
                if (StringUtils.isNullOrEmpty(reward.getUnionUid())) {
                    continue;
                }
                eHonorsActivityType activityType = eHonorsActivityType.getHonorsType(reward.getActivityType(), reward.getActivityChildType());
                if (activityType == null) {
                    continue;
                }
                if (reward.getRank() <= 0) {
                    continue;
                }
                int honors = 0;

                Map<Integer, Integer> rewardMap = getHonorRewardMapByActivity(reward.getServerList().size(), activityType);
                int honorLevel = Integer.MAX_VALUE;
                //找到当前排名满足的最高级别奖励
                for (Map.Entry<Integer, Integer> entry : rewardMap.entrySet()) {
                    if (reward.getRank() <= entry.getKey()) {      //Map<最低排名,奖励>
                        if (honorLevel > entry.getKey()) {
                            honorLevel = entry.getKey();
                        }
                    }
                }
                if (!rewardMap.keySet().contains(honorLevel)) {
                    getLogger().debug("sendReward honors zero, {} {}", reward.getActivityId(), reward.getServerList());
                    continue;
                }

                honors = rewardMap.get(honorLevel);
                if (honors > 0 && reward.getServerList().size() > 0) {
                    reward.setHonors(honors);

                    //跨服增加历史荣誉
                    CrossUnionHonorsProto.CrossUnionGetHonorsUploadMsg.Builder reqMsg = CrossUnionHonorsProto.CrossUnionGetHonorsUploadMsg.newBuilder();
                    reqMsg.setUnionUid(reward.getUnionUid());
                    reqMsg.setActivityId(reward.getActivityId());
                    CrossUnionHonorsProto.UnionHistoryHonorsRecordTemp.Builder builder = CrossUnionHonorsProto.UnionHistoryHonorsRecordTemp.newBuilder();
                    builder.setHonors(honors);
                    builder.setGetTime(DateHelper.getCurrentSecond());
                    builder.setActivityType(reward.getActivityType());
                    builder.setActivityChildType(reward.getActivityChildType());
                    builder.addAllServerList(reward.getServerList());
                    builder.setRank(reward.getRank());//4.9优化 要带排名了
                    reqMsg.setRecord(builder);
                    MessageHelper.sendPacket(reward.getServerId(), 0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_HONORS_GET_UPLOAD, reqMsg));

                    reward.setSend(true);
                    getLogger().debug("sendReward honors {}", JSON.toJSONString(reward));
                } else {
                    getLogger().debug("sendReward honors zero, {} {}", reward.getActivityId(), reward.getServerList());
                }
            }

        }


    }

    /**
     * 通过服务器数量与跨服商会活动类型提取出奖励 Map<最高排名,奖励荣誉点>   配置很恶心，以后看看能不能改或者拆了
     */
    public static Map<Integer, Integer> getHonorRewardMapByActivity(int serverListSize, eHonorsActivityType activityType) {
        String rankInfo = null;
        //<最高名次,奖励>
        Map<Integer, Integer> rewardMap = new LinkedHashMap<>();
        //分割不同活动类型 (string)|(string)|(string)
        List<String> typeParamList = StringUtils.stringToStringList(GameConfig.BANNER_RANK_HONOR_REWARD, "\\|");
        for (String typeParam : typeParamList) {
            //活动类型(int)#rankinfo(string)
            int index = typeParam.indexOf('#');
            int type = Integer.valueOf(typeParam.substring(0, index));
            if (type == activityType.getHonorsType()) {
                rankInfo = typeParam.substring(index + 1);
                break;
            }
        }

        //rankinfo  最小服,最大服=第一档名次,奖励;第二档名次,奖励;...#最小服,最大服=第一档名次,奖励;第二档名次,奖励;...
        if (!StringUtils.isNullOrEmpty(rankInfo)) {
            List<String> differentServerSizeList = StringUtils.stringToStringList(rankInfo, "#");
            //rankString 最小服,最大服=第一档名次,奖励;第二档名次,奖励;第三档名次,奖励
            for (String rankString : differentServerSizeList) {
                List<String> serverSize_Reward = StringUtils.stringToStringList(rankString, "=");
                // itemList (服务器数量最小值,服务器数量最大值)
                List<Integer> itemList = StringUtils.stringToIntegerList(serverSize_Reward.get(0), ",");
                if (serverListSize >= itemList.get(0) && serverListSize <= itemList.get(1)) {
                    //differentRankList(最高排名,奖励;最高排名,奖励)
                    List<String> differentRankList = StringUtils.stringToStringList(serverSize_Reward.get(1), ";");
                    //rankDetail (最高排名,奖励)
                    for (String rankDetail : differentRankList) {
                        List<Integer> rank_reward = StringUtils.stringToIntegerList(rankDetail, ",");
                        rewardMap.put(rank_reward.get(0), rank_reward.get(1));
                    }
                    break;
                }
            }
        }
        return rewardMap;
    }

    public static void addHonor() {

    }

    public static int getLowestRewardRank(int serverSize, eHonorsActivityType type) {
        Map<Integer, Integer> rewardConfigMap = getHonorRewardMapByActivity(serverSize, type);
        if (rewardConfigMap.isEmpty()) {
            getLogger().error("Honors Config error at serverSize {} eHonorsActivityType ", serverSize, type);
        }
        int lowestRewardRank = 1;
        //找出最多要前几名领奖
        for (Map.Entry<Integer, Integer> entry : rewardConfigMap.entrySet()) {
            if (entry.getKey() > lowestRewardRank) {
                lowestRewardRank = entry.getKey();
            }
        }
        return lowestRewardRank;
    }

    public static Map<Integer, Map<Integer, UnionActivityHonorsReward>> getRewardMap() {
        return rewardMap;
    }

    public static void reSendReward(int activityId) {
        Map<Integer, UnionActivityHonorsReward> rankRewardMap = rewardMap.get(activityId);
        if (rankRewardMap != null) {
            for (UnionActivityHonorsReward unionActivityHonorsReward : rankRewardMap.values()) {
                unionActivityHonorsReward.setSend(false);
            }
        }
    }
}
